#include "chessboard.h"
#include "commdef.h"
#include <QPainter>
#include <QDebug>

ChessBoard::ChessBoard(QWidget *parent) : QWidget(parent)
{
    resize(CHESSBOARD_WIDTH, CHESSBOARD_HEIGHT);
    move(CHESSBOARD_STARTX, CHESSBOARD_STARTY);
    fliped = false;
    loadPixmap(STARTUP_LAYOUT);
}

ChessBoard::~ChessBoard()
{
}

//此函数在棋盘的行和列上迭代，从arrChessman数组中检索每个棋子的相应像素图，并将其绘制在小部件的适当位置。背景图像也绘制在函数的开头。
void ChessBoard::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    int xx = 0;
    int yy = 0;
    int index = 0;

    QPainter painter(this);
    //绘制背景图
    painter.drawPixmap(0, 0, background);

    for (int row = 0; row < CHESSBOARD_ROW; ++row)
    {
        for (int column = 0; column < CHESSBOARD_COLUMN; ++column)
        {
            index = row * CHESSBOARD_COLUMN + column;
            getPixmapPos(row, column, xx, yy);
            //绘制棋子
            painter.drawPixmap(xx, yy ,arrChessman[index]);
        }
    }
}

//此功能捕获棋盘上的鼠标按下事件，确定鼠标点击发生的方格，计算阵列中棋子的索引，并发出信号以启动与所选棋子的移动。
void ChessBoard::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        int row = 0;
        int column = 0;
        getPixmapIndex(event->pos().x(), event->pos().y(), row, column);

        int sq = getChessmanIndex(row, column, fliped);
        //该信号与所选棋子的索引一起发出，以通知所连接的插槽应该使用该棋子进行移动
        emit doMove(sq);
    }
}

void ChessBoard::loadPixmap(const char *chessman)
{
    int sq = 0;   //存储棋子的索引
    char pc = 0;   //存储棋子的字符
    int index = 0;   //用于存储arrChessman数组中棋子的索引

//    background.load(":/images/WOOD.GIF");
//    for(int row = 0; row < CHESSBOARD_ROW; ++row)
//    {
//        for (int column = 0; column < CHESSBOARD_COLUMN; ++column)
//        {
//            index = row * CHESSBOARD_COLUMN + column;
//            sq = getChessmanIndex(row, column, fliped);
//            pc = chessman[sq];
//            //将角色pc代表的棋子的像素图图像加载到棋盘的当前正方形上。
//            arrChessman[index].load(getChessmanPic(pc, false, false));

//        }
//    }
}


void ChessBoard::showMoveRoute(char movingChessman, int move, bool show)
{
    int srcPos = SRC(move);
    int dstPos = DST(move);
    int srcIndex = 0;
    int dstIndex = 0;

    if (srcPos > 0)
    {
        //根据源位置的文件（列）和等级（行）以及棋盘是否翻转，计算棋盘上源位置的索引。
        srcIndex = getChessboardCoord(FILE_X(srcPos), RANK_Y(srcPos), fliped);
        //加载源位置的像素图图像：
        arrChessman[srcIndex].load(getChessmanPic(dstPos > 0 ? 0 : movingChessman, show, false));
    }

    if (dstPos > 0)
    {
        dstIndex = getChessboardCoord(FILE_X(dstPos), RANK_Y(dstPos), fliped);
        arrChessman[dstIndex].load(getChessmanPic(movingChessman, show, false));
    }
}

void ChessBoard::updateGeneralDisplay(char chessman, int pos, bool dead)
{
    int index = getChessboardCoord(FILE_X(pos), RANK_Y(pos), fliped);
    //根据棋子的类型、状态（显示）和是否已死亡（捕获）来检索棋子的像素图图像。
    arrChessman[index].load(getChessmanPic(chessman, true, dead));
}

void ChessBoard::changeFlip()
{
    fliped = !fliped;
}
